package org.example.myleet.p427;

import org.example.myleet.Utils.Assert;
import org.example.myleet.Utils.Parser;

import java.util.Deque;
import java.util.LinkedList;

public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        Assert.isTrue("[[0,1],[1,0],[1,1],[1,1],[1,0]]".equals(serialize(solution.construct(Parser.parse("[[0,1],[1,0]]")))));
        Assert.isTrue("[[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]".equals(serialize(solution.construct(Parser.parse("[[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]")))));
        Assert.isTrue("[[1,1]]".equals(serialize(solution.construct(Parser.parse("[[1,1],[1,1]]")))));
        Assert.isTrue("[[1,0]]".equals(serialize(solution.construct(Parser.parse("[[0]]")))));
        Assert.isTrue("[[0,1],[1,1],[1,0],[1,0],[1,1]]".equals(serialize(solution.construct(Parser.parse("[[1,1,0,0],[1,1,0,0],[0,0,1,1],[0,0,1,1]]")))));
        Assert.isTrue("[[0,1],[0,1],[0,1],[0,1],[0,1],[1,1],[1,1],[1,0],[1,0],[1,0],[1,0],[1,1],[1,1],[1,1],[1,1],[1,0],[1,0],[1,0],[1,0],[1,1],[1,1]]".equals(serialize(solution.construct(Parser.parse("[[1,1,0,0],[0,0,1,1],[1,1,0,0],[0,0,1,1]]")))));
    }

    private static String serialize(Node root) {
        Deque<Node> deque = new LinkedList<>();
        Deque<int[]> result = new LinkedList<>();
        deque.offer(root);
        while (!deque.isEmpty()) {
            int size = deque.size();
            for (int i = 0; i < size; ++i) {
                Node cur = deque.poll();
                if (null == cur) {
                    result.offer(null);
                } else {
                    result.offer(new int[]{bool2int(cur.isLeaf), bool2int(cur.val)});
                    deque.offer(cur.topLeft);
                    deque.offer(cur.topRight);
                    deque.offer(cur.bottomLeft);
                    deque.offer(cur.bottomRight);
                }
            }
        }
        while (null == result.peekLast()) {
            result.pollLast();
        }
        StringBuilder sb = new StringBuilder();
        sb.append('[');
        while (!result.isEmpty()) {
            int[] cur = result.poll();
            if (null == cur) {
                sb.append("null");
            } else {
                sb.append('[').append(cur[0]).append(',').append(cur[1]).append(']');
            }
            sb.append(',');
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append(']');
        return sb.toString();
    }

    private static int bool2int(boolean b) {
        return b ? 1 : 0;
    }
}
